package com.sso.common;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;

import com.tools.util.StrUtils;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.exception.ParseErrorException;
import org.apache.velocity.exception.ResourceNotFoundException;


public class VelocityUtil {
    public static final String ERROR = "F";
    public static final String SUCCESS = "T";

    /**
     * 2016-1-12
     *
     * @param filePath    文件所在相对路径，默认WEB_INF/views/文件夹下指定路径的模板
     * @param outPath     文件输出相对路径，默认输出在WEB_INF/views/文件夹下指定的路径及文件名
     * @param newFileName
     * @param param
     * @return
     */
    public static String outStaticHtml(String filePath, String outPath, String newFileName, Map<String, Object> param, HttpServletRequest request) {
        String basePath = request.getSession().getServletContext().getRealPath("") + File.separator + "WEB-INF" + File.separator + "views";
        if (StrUtils.isEmpty(filePath)) {
            return ERROR;
        }
        if (StrUtils.isEmpty(outPath)) {
            return ERROR;
        }
        filePath = replace("/|\\\\", filePath, File.separator);  //转换为标准路径
        outPath = replace("/|\\\\", outPath, File.separator);    //转换为标准路径
        //获取基础绝对路径
        try {
            //初始化Velocity模板参数
            Properties p = new Properties();
            VelocityEngine engine = new VelocityEngine();
            p.setProperty(VelocityEngine.FILE_RESOURCE_LOADER_PATH, basePath);  //读取本地模板
            engine.init(p);
            Template template = engine.getTemplate(filePath, "UTF-8");
            VelocityContext context = getContext(param);
            //读取输出路径创建输出流
            PrintWriter pw = new PrintWriter(basePath + outPath);
            //输出
            template.merge(context, pw);
            pw.close();
            return SUCCESS;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return ERROR;
        } catch (ResourceNotFoundException e) {
            e.printStackTrace();
            return ERROR;
        } catch (ParseErrorException e) {
            e.printStackTrace();
            return ERROR;
        }
    }

    /**
     * 处理map参数
     * 2016-1-12
     *
     * @param param
     * @return
     */
    private static VelocityContext getContext(Map<String, Object> param) {
        VelocityContext context = new VelocityContext();
        if (param == null || param.size() == 0) {
            return context;
        }
        Set<String> keys = param.keySet();
        Iterator<String> it = keys.iterator();
        while (it.hasNext()) {
            String key = it.next();
            Object value = param.get(key);
            context.put(key, value);
        }
        return context;
    }

    private static String replace(String regex, String oldStr, String newStr) {
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(oldStr);
        return matcher.replaceAll(Matcher.quoteReplacement(newStr));
    }
}
